package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.ItemDetail;
import com.github.postsanf.yinian.bean.VoiceCardOrder;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.myzxing.utils.QRCodeUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.widget.MyEditText;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.UUID;

public class VoiceCardPreViewActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_back;
    private TextView voicecard_order;
    private SimpleDraweeView time_card_edit_cover_pic;
    private SimpleDraweeView iv_voice_pic;
    private RelativeLayout voice_card_edit_kuang;
    private RelativeLayout ll_text;
    private TextView tv_to_name;
    private LinearLayout myedittext_voicecard;
    private TextView tv_from_name;
    private ImageView iv_turn_cover;
    private MyEditText myEditText;
    private ImageView iv_voice;
    private UploadManager mUpManager;
    private String micurl;
    private String voiceWord;
    private String voiceFromName;
    private String voiceToName;
    private String voiceCoverPicUrl;
    private String voicePicUrl;
    private String voicePicUrlkey;
    private String jieTuUrl;
    private String jieTuUrlkey;
    private int audiotime;
    private ProgressDialog mProgressDialog;
    private File f;
    private TextView tv_to;
    private TextView tv_from;
    private String erQrfilePath;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_card_pre_view);
        mUpManager = application.getUploadManager();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_UP);
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID != null) {
            initData();
        } else {
            initView(null);
        }
    }

    private void initData() {
        mProgressDialog = ProgressDialog.show(VoiceCardPreViewActivity.this, "", "正在加载中...");
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID == null) {
            showToast("信息加载出错请稍后重试...");
            return;
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_ITEM_ID, itemID);
        StringRequest req = new StringRequest(getString(R.string.SHOP_URL) + getString(R.string.ynGetItemDetail))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ItemDetail itemDetail = gson.fromJson(s, ItemDetail.class);
                        if (itemDetail.getMsg().equals("success")) {
                            ItemDetail.DataBean dataBean = itemDetail.getData().get(0);
                            initView(dataBean);
                        } else {
                            showToast(itemDetail.getMsg());
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void initView(ItemDetail.DataBean dataBean) {
        voicecard_order = ((TextView) findViewById(R.id.voicecard_order));
        voicePicUrl = getIntent().getStringExtra("voicepic");
        voiceCoverPicUrl = getIntent().getStringExtra("voiceCoverPic");
        voiceToName = getIntent().getStringExtra("voiceToName");
        voiceFromName = getIntent().getStringExtra("voiceFromName");
        audiotime = getIntent().getIntExtra("audiotime", 0);
        voiceWord = getIntent().getStringExtra("voiceContent");
        micurl = getIntent().getStringExtra("micurl");
        String itemID = getIntent().getStringExtra("itemID");
        if (itemID != null) {
            voicecard_order.setVisibility(View.GONE);
            voicePicUrl = dataBean.getItemPic().get(0) + "?imageView2/2/w/300";
            voiceCoverPicUrl = dataBean.getItemCover() + "?imageView2/2/w/300";
            voiceToName = dataBean.getItemTo();
            voiceFromName = dataBean.getItemFrom();
            voiceWord = dataBean.getItemText();
            micurl = dataBean.getItemAudio();
            if (dataBean.getItemAudioTime() != null) {
                audiotime = Integer.parseInt(dataBean.getItemAudioTime());
            }
        } else {
            voicecard_order.setVisibility(View.VISIBLE);
        }
        final String url = "http://wx.zhuiyinanian.com/shop/playaudio?src=" + "http://7xlmtr.com1.z0.glb.clouddn.com/" + micurl + "&goodsid=1";
        boolean mp3IsExist = getIntent().getBooleanExtra("mp3IsExist", false);
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        voice_card_edit_kuang = (RelativeLayout) findViewById(R.id.voice_card_edit_kuang);
        LinearLayout.LayoutParams kuangParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, UIHelper.getVoiceCardHigh(this));
        kuangParams.setMargins(UIHelper.dip2px(this, 10), UIHelper.dip2px(this, 20), UIHelper.dip2px(this, 10), 0);
        voice_card_edit_kuang.setLayoutParams(kuangParams);
        time_card_edit_cover_pic = ((SimpleDraweeView) findViewById(R.id.time_card_edit_cover_pic));
        iv_voice_pic = ((SimpleDraweeView) findViewById(R.id.iv_voice_pic));
        RelativeLayout.LayoutParams picParams = new RelativeLayout.LayoutParams(UIHelper.getVoiceCardPicWidth(this), UIHelper.getVoiceCardPicHigh(this));
        picParams.addRule(RelativeLayout.CENTER_VERTICAL);
        picParams.leftMargin = UIHelper.dip2px(this, 20);
        iv_voice_pic.setLayoutParams(picParams);
        ll_text = ((RelativeLayout) findViewById(R.id.ll_text));
        myedittext_voicecard = ((LinearLayout) findViewById(R.id.myedittext_voicecard));
        iv_voice = ((ImageView) findViewById(R.id.iv_voice));
        iv_turn_cover = ((ImageView) findViewById(R.id.iv_turn_cover));
        tv_to = ((TextView) findViewById(R.id.tv_to));
        tv_to_name = ((TextView) findViewById(R.id.tv_to_name));
        tv_to.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_to_name.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_to.setText("To:");
        tv_from = ((TextView) findViewById(R.id.tv_from));
        tv_from_name = ((TextView) findViewById(R.id.tv_from_name));
        tv_from.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_from_name.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        tv_from.setText("From:");
        iv_back.setOnClickListener(this);
        voicecard_order.setOnClickListener(this);
        iv_turn_cover.setOnClickListener(this);
        ImageOptHelper.showFrescoTodayshow(Uri.parse(YNUrlHelper.getCoverUrl2(VoiceCardPreViewActivity.this, voiceCoverPicUrl)), time_card_edit_cover_pic, VoiceCardPreViewActivity.this);
        if (itemID == null && voicePicUrl != null) {
            ImageOptHelper.showFrescoVoicePic(Uri.parse("file://" + voicePicUrl), iv_voice_pic, VoiceCardPreViewActivity.this);
        } else {
            ImageOptHelper.showFrescoVoicePic(Uri.parse(voicePicUrl), iv_voice_pic, VoiceCardPreViewActivity.this);
        }
        if (mp3IsExist || audiotime > 0) {
            erQrfilePath = getFileRoot(VoiceCardPreViewActivity.this) + File.separator
                    + "qr_" + System.currentTimeMillis() + ".jpg";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean success = QRCodeUtil.createQRImage(url, UIHelper.dip2px(VoiceCardPreViewActivity.this, 75), UIHelper.dip2px(VoiceCardPreViewActivity.this, 75), null, erQrfilePath);
                    if (success) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv_voice.setImageBitmap(BitmapFactory.decodeFile(erQrfilePath));
                            }
                        });
                    }
                }
            }).start();
        } else {
            iv_voice.setVisibility(View.GONE);
        }
        tv_to_name.setText(voiceToName);
        tv_from_name.setText(voiceFromName);
        myedittext_voicecard.removeAllViews();
        myEditText = new MyEditText(this, Color.parseColor("#00000000"), 2.0f);
        myEditText.setTextColor(getResources().getColor(R.color.timecard_from_txcolor_drak));
        myEditText.setTextSize(10);
        myEditText.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        myEditText.setText(voiceWord);
        myedittext_voicecard.addView(myEditText);
        time_card_edit_cover_pic.setVisibility(View.GONE);
        ll_text.setVisibility(View.VISIBLE);
        iv_voice_pic.setVisibility(View.VISIBLE);
    }

    private boolean turn = true;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.voicecard_order:
                mProgressDialog.show();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mProgressDialog.setMessage("网络连接出错，请您检查网络连接后重新下单！");
                        mProgressDialog.dismiss();
                    }
                }, 1000 * 60);
                DoJieTu();
                break;
            case R.id.iv_turn_cover:
                if (turn) {
                    time_card_edit_cover_pic.setVisibility(View.VISIBLE);
                    ll_text.setVisibility(View.GONE);
                    iv_voice_pic.setVisibility(View.GONE);
                    turn = false;
                } else {
                    time_card_edit_cover_pic.setVisibility(View.GONE);
                    ll_text.setVisibility(View.VISIBLE);
                    iv_voice_pic.setVisibility(View.VISIBLE);
                    turn = true;
                }
                break;
        }
    }

    //文件存储根目录
    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return context.getFilesDir().getAbsolutePath();
    }

    private void goToOrder() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GOODS_ID, String.valueOf(1));
        mParam.put(CommonConstants.PICTURE, voicePicUrlkey);
        if (micurl != null) {
            mParam.put(CommonConstants.AUDIO, micurl);
            mParam.put(CommonConstants.AUDIOTIME, String.valueOf(audiotime));
        }
        if (voiceFromName != null) {
            mParam.put(CommonConstants.FROM, voiceFromName);
        }
        if (voiceToName != null) {
            mParam.put(CommonConstants.TO, voiceToName);
        }
        if (voiceWord != null) {
            mParam.put(CommonConstants.CONTENT, voiceWord);
        }
        mParam.put(CommonConstants.COVER, voiceCoverPicUrl);
        // mParam.put(CommonConstants.RESULT, jieTuUrlkey);
        // Log.i("xjs", "jieTuUrlkey====>" + jieTuUrlkey);
        Log.i("xjs", "voicePicUrlkey====>" + voicePicUrlkey);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/eb/AddItem")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        VoiceCardOrder voiceCardOrder = gson.fromJson(s, VoiceCardOrder.class);
                        if (TextUtils.equals(voiceCardOrder.getMsg(), "success")) {
                            Log.i("xjs", "sssspps==>" + s.toString());
                            mProgressDialog.dismiss();
                            String itemid = voiceCardOrder.getData().get(0).getItemID();
                            String couponPrice = voiceCardOrder.getData().get(0).getCouponPrice();
                            String postage = voiceCardOrder.getData().get(0).getPostage();
                            Intent intent = new Intent(VoiceCardPreViewActivity.this, OrderActivity.class);
                            intent.putExtra("couponPrice", couponPrice);
                            intent.putExtra("postage", postage);
                            intent.putExtra("itemid", itemid);
                            intent.putExtra("micurl", micurl);
                            intent.putExtra("goodsid", 1);
                            startActivity(intent);
//                            sendBroadcast(new Intent(ACTIONs.actionCloseVoiceCard));
//                            finish();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (f != null && f.exists()) {
//            f.delete();
//        }
        File file = new File(voicePicUrl);
        if (file.exists()) {
            file.delete();
        }
    }

    private void DoJieTu() {
//        Bitmap res = getResPhoto();
//        saveBitmapres(res);
//         saveBitmap(voice_card_edit_kuang);
//        if (f.exists()) {
//            getTokenJieTu();
//        }
        getTokenCover();
    }

    public void saveBitmapres(Bitmap bm) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
        jieTuUrl = f.getAbsolutePath();
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Bitmap getResPhoto() {
        int width = 1776;
        int height = 1185;
        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawColor(Color.WHITE);
        if (!StringUtils.isEmpty(voicePicUrl) && new File(voicePicUrl).exists()) {
            canvas.drawBitmap(ImageUtils.zoomImg(BitmapFactory.decodeFile(voicePicUrl), 884, 884), 43, 132, null);
        }
        if (!StringUtils.isEmpty(erQrfilePath) && new File(erQrfilePath).exists()) {
            canvas.drawBitmap(ImageUtils.zoomImg(BitmapFactory.decodeFile(erQrfilePath), 178, 178), 1060, 704, null);
        }
        Paint p = new Paint();
        p.setColor(Color.BLACK);
        p.setAntiAlias(true);   //去除锯齿
        p.setFilterBitmap(true);//对位图进行滤波处理
        p.setTextSize(48F);
        p.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        canvas.drawText("To  " + voiceToName + " ：", 1010, 160, p);
        String fromtt = "From : " + voiceFromName;
        int textWidth = width - (int) p.measureText(fromtt) - 75;
        canvas.drawText(fromtt, textWidth, 956, p);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(48.0F);
        textPaint.setTypeface(Typeface.createFromAsset(getAssets(), "fzjl.TTF"));
        StaticLayout layout = new StaticLayout(voiceWord, textPaint, 530, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
        canvas.translate(1060, 306);
        layout.draw(canvas);
        return result;
    }

    public void saveBitmap(View v) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
        jieTuUrl = f.getAbsolutePath();
        if (f.exists()) {
            f.delete();
        }
        Bitmap bm = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        v.draw(canvas);
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取上传Token
    private void getTokenCover() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            String prefix = voicePicUrl.substring(voicePicUrl.lastIndexOf(".") + 1);
                            final String imgName = UUID.randomUUID().toString() + "." + prefix;
                            mUpManager.put(voicePicUrl, imgName, resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {

                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                            Log.i("xjs", "UploadOptions");
                                            if (percent == 1.0) {
                                                voicePicUrlkey = key;
                                                goToOrder();
                                            }
                                        }
                                    }, null));
                        } else {
                            mProgressDialog.dismiss();
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void getTokenJieTu() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            mUpManager.put(jieTuUrl, UUID.randomUUID().toString() + ".png", resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                            if (percent == 1.0) {
                                                jieTuUrlkey = key;
                                                getTokenCover();
                                            }
                                        }
                                    }, null));
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
